#include <iostream>
#include <string>

#include <cstring>
#include <cstdio>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

// .udp_client ip port
static void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " ip port\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    // client不需要主动bind，这是一个客户端，普通用户不知道，如果程序员写了bind，那么一定bind了一个固定的端口号
    // 如果这个端口号被其他进程占用了呢，所以就让OS自动随机选择端口号

    std::string message;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    char buffer[1024];
    while (true)
    {
        std::cout << "请输入:";
        std::getline(std::cin, message);
        // 当client首次发送消息给服务器的时候，OS会自动给client bind他的IP和PORT
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        // 读取
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &len);
        if (s > 0)
        {
            std::cout << "Server echo# " << buffer << std::endl;
        }
    }
    return 0;
}